package clientService;

import common.Message;
import common.MessageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * @author lhn
 * @date 2024-05-15 14:57
 * 提供和消息相关的服务方法
 */

public class MessageClientService {
    /**
    * @author lihaonan
    * @date 2024/5/15 14:59
     * @param content   内容
     * @param senderId  发送者ID
     * @param getterId  接收者ID
    */
    public void sendMessageToOne(String content, String senderId, String getterId) {
        Message message = new Message();
        message.setSender(senderId);
        message.setGetter(getterId);
        message.setContent(content);
        message.setMesType(MessageType.MESSAGE_COMMON_MESSAGE);
        message.setSendTime(
                new Date().toString()
        );
        System.out.println(message.getSendTime() + ": 我(" + senderId + ")对用户" + getterId + "说" + content);
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                    ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket().getOutputStream()
            );
            objectOutputStream.writeObject(message);    //发送给服务端

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
    * @author lihaonan
    * @date 2024/5/15 19:52
     * @param senderId  发送者ID
    */
    public void sendMessageToAll(String content, String senderId) {
        Message message = new Message();
        message.setSender(senderId);
        message.setContent(content);
        message.setMesType(MessageType.MESSAGE_COMMON_MESSAGE_ALL);
        message.setSendTime(
                new Date().toString()
        );
        System.out.println(message.getSendTime() + ": 我(" + senderId + ")对所有用户" + "说" + content);
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                    ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket().getOutputStream()
            );
            objectOutputStream.writeObject(message);    //发送给服务端

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
